import 'dart:async';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:get/get.dart';

class EmailVerificationLogic extends BaseController {
  // 邮箱地址
  final String email = Get.arguments?['email'] ?? 'e';

  // 密码
  final String password = Get.arguments?['password'] ?? '';

  // // 验证类型
  final String type = Get.arguments?['type'] ?? 'register';

  // 验证码
  String verificationCode = '';

  // 错误标记
  bool hasError = false;

  // 倒计时
  bool isCountingDown = false;
  int countdownSeconds = 60;
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    // 初始化时发送验证码
    _sendVerifyCode();
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  // 发送验证码
  Future<void> _sendVerifyCode() async {
    HttpResponse response = await HttpManager().post(
      API.sendVerifyCode,
      params: {'email': email, 'type': type},
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      LoadingUtils.showToast('Verification code sent');
      _startCountdown();
    }
  }

  // 开始倒计时
  void _startCountdown() {
    isCountingDown = true;
    countdownSeconds = 60;
    update();

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdownSeconds--;
      update();
      if (countdownSeconds <= 0) {
        timer.cancel();
        isCountingDown = false;
        update();
      }
    });
  }

  // 验证码输入变化
  void onCodeChanged(String code) {
    verificationCode = code;

    // 当用户开始输入时，清除错误状态
    if (hasError) {
      hasError = false;
      update();
    }
  }

  // 验证输入的验证码
  Future<void> verifyCode(String code) async {
    verificationCode = code;

    if (verificationCode.length != 6) {
      hasError = true;
      update();
      return;
    }

    // 根据类型调用不同的接口
    if (type == 'register') {
      await _handleRegister();
    } else if (type == 'reset') {
      await _handleForgotPassword();
    }
  }

  // 处理注册验证
  Future<void> _handleRegister() async {
    // 调用注册接口
    HttpResponse response = await HttpManager().post(
      API.register,
      params: {'email': email, 'code': verificationCode, 'password': password},
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      // 注册成功，跳转到注册成功页面
      Get.offAllNamed(AppRoutes.registerSuccess);
    } else {
      // 注册失败，显示错误状态
      hasError = true;
      update();
    }
  }

  // 处理忘记密码验证
  Future<void> _handleForgotPassword() async {
    // 当type为forget时，不调用接口，直接跳转到重置密码页面
    Get.toNamed(AppRoutes.resetPassword, arguments: {
      'email': email,
      'code': verificationCode
    });
  }

  // 重新发送验证码
  Future<void> resendCode() async {
    if (isCountingDown) return;

    // 重新发送验证码
    _sendVerifyCode();
  }
}
